package com.cincc.cincc_pbx.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.cincc.cincc_pbx.R;
import com.cincc.cincc_pbx.adapter.ExternalAdapter;
import com.cincc.cincc_pbx.common.CallUtil;
import com.cincc.cincc_pbx.common.MyUtils;
import com.cincc.cincc_pbx.common.OkHttpUtils;
import com.cincc.cincc_pbx.common.callback.IDialogCallback;
import com.cincc.cincc_pbx.constant.CallConstant;
import com.cincc.cincc_pbx.model.ExternalContactModel;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class ExternalActivity extends BaseActivity {
    private static final String TAG = "ExternalActivity";

    @Override
    protected void afterViews() {
        super.afterViews();
        initView();
        requestData();
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_external_contact;
    }

    int type = 0;
    RecyclerView recyclerView;
    ExternalAdapter externalAdapter;

    private void initView() {
        //0 企业  1 我的
        type = getIntent().getIntExtra("type", 0);

        TextView textView = findViewById(R.id.title_tv);
        textView.setText(type == 0 ? "企业外部联系人" : "我的外部联系人");

        recyclerView = findViewById(R.id.recycler);
        recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));

        externalAdapter = new ExternalAdapter(this, list);
        recyclerView.setAdapter(externalAdapter);
        externalAdapter.setOnClickItem(item -> {
            showDialog(item.getName(), item.getPhone());
        });
    }

    private void requestData() {
        try {
            String memberId = type == 0 ? "0" : CallConstant.loginModel.getUserId();
            String vccId = CallConstant.loginModel.getVccId();
            JSONObject params = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("vccId", vccId);
            jsonObject.put("memberId", memberId);
            jsonObject.put("pageNum", 1);
            jsonObject.put("pageSize", 1000);
            params.put("params", jsonObject);
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", "Bearer " + CallConstant.loginModel.getAccessToken());
            OkHttpUtils.httpPost(CallConstant.REQUEST_EXTERNAL_CONTACT_URL, params.toString(), header, new OkHttpUtils.ICallBack() {
                @Override
                public void onSuccessful(Call call, String data) {
                    Log.e(TAG, "getExternal onSuccessful: " + data);
                    runOnUiThread(() -> {
                        refreshUI(data);
                    });
                }

                @Override
                public void onFailure(Call call, String errorMsg) {
                    Log.e(TAG, "getExternal onFailure: " + errorMsg);
                    runOnUiThread(() -> Toast.makeText(ExternalActivity.this, errorMsg, Toast.LENGTH_SHORT).show());
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "getExternal onFailure: " + e.getMessage());
            runOnUiThread(() -> Toast.makeText(ExternalActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }

    private void showDialog(String name, String phone) {
        MyUtils.showConfirmDialog(this, "确定要呼叫" + name + "吗？电话号码:" + phone, new IDialogCallback() {
            @Override
            public void confirm() {
                applyPermission(phone);
            }

            @Override
            public void cancel() {

            }
        });
    }

    private void applyPermission(String phone) {
        XXPermissions.with(this).permission(CallConstant.AUDIO_PERMISSION_LIST)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            Toast.makeText(ExternalActivity.this, "请授予全部权限，否则无法使用通话功能", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        openCall(phone);
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            Toast.makeText(ExternalActivity.this, "被永久拒绝授权，请手动授予对应权限", Toast.LENGTH_SHORT).show();
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(ExternalActivity.this, permissions);
                        } else {
                            System.out.println("授予权限失败");
                        }
                    }
                });
    }

    private void openCall(String callNumber) {
        CallUtil.getInstance().makeCall(callNumber);
        Intent i = new Intent(this, CallActivity.class);
        i.putExtra("callNumber", callNumber);
        startActivity(i);
    }

    List<ExternalContactModel> list = new ArrayList<>();

    private void refreshUI(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            if (jsonObject.getString("rtnCode").equals("0000")) {
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                for (int i = 0; i < jsonArray.length(); i++) {
                    String id = jsonArray.getJSONObject(i).getString("id");
                    String conName = jsonArray.getJSONObject(i).getString("conName");
                    String firm = jsonArray.getJSONObject(i).getString("firm");
                    String posts = jsonArray.getJSONObject(i).getString("posts");
                    JSONArray phoneArray = jsonArray.getJSONObject(i).getJSONArray("phone");
                    String phone = "";
                    if (phoneArray.length() > 0) {
                        phone = phoneArray.getJSONObject(0).getString("value");
                    }
                    ExternalContactModel model = new ExternalContactModel(id, conName, firm, posts, phone);
                    list.add(model);
                }
                externalAdapter.notifyDataSetChanged();
            } else {
                String msg = jsonObject.getString("rtnMsg");
                Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}
